// import { readJson, writeJSON } from '../util/PromiseJson.js'
import path from 'path'
import __dirname from '../util/dirname.js'
import fs from 'fs'
// import { promisify } from 'util'
// const readdir = promisify(fs.readdir)
import formidable from 'formidable'

const upload = async (req, res) => {
  const form = formidable({ uploadDir: path.resolve(__dirname, '../assets/images/temp'), keepExtensions: true })
  form.parse(req, (uploadErr, fields, files) => {
    if (uploadErr) return res.send({ code: 500, msg: '上传过程出错' })
    const { type } = fields
    const md = `/assets/images/${type}`
    const { file } = files
    const p = file.path
    const index = p.lastIndexOf('\\')
    const name = p.slice(index)
    const destPath = path.join(__dirname, `../${md}`, name)

    fs.rename(p,destPath,err=>{
      if(err) return res.send({code:500,msg:'转移过程失败'})
      res.send({ code: 200, msg: 'ok', data: `${res.res_baseUrl}${md}${name}` })
    })

  })
}

export { upload }